package com.ncloud.system.service.impl;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.ncloud.common.exception.UserException;
import com.ncloud.system.service.FileService;

@Service
public class FileServiceImpl implements FileService{

	@Value("${file.head.path:/head/upload}")
	public String pathDir;

	@Override
	public String headUpload(MultipartFile file) {
		String fileName = "";
		if (!file.isEmpty()) {
			String path = getPath();
			File pathFile = new File(path);
			if (!pathFile.exists() && !pathFile.isDirectory()) {
				pathFile.mkdirs();
			}
			fileName = path + file.getOriginalFilename();
			File targetFile = new File(fileName);

			if (targetFile.exists() && !targetFile.isDirectory()) {
				throw new UserException(4001, "附件已经存在");
			}
			try {
				file.transferTo(targetFile);
			} catch (IllegalStateException | IOException e) {
				throw new UserException(4002, "上传失败");
			}
		} else {
			throw new UserException(4003, "传入文件为空");
		}
		return fileName;
	}
	
	@Override
	public String headUpload2Server(MultipartFile file) {
		String fileName = "";
		if (!file.isEmpty()) {
			try {
				byte[] fileb = file.getBytes();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			String path = getPath();
			File pathFile = new File(path);
			if (!pathFile.exists() && !pathFile.isDirectory()) {
				pathFile.mkdirs();
			}
			fileName = path + file.getOriginalFilename();
			File targetFile = new File(fileName);

			if (targetFile.exists() && !targetFile.isDirectory()) {
				throw new UserException(4001, "附件已经存在");
			}
			try {
				file.transferTo(targetFile);
			} catch (IllegalStateException | IOException e) {
				throw new UserException(4002, "上传失败");
			}
		} else {
			throw new UserException(4003, "传入文件为空");
		}
		return fileName;
	}

	private String getPath() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		String dateString = formatter.format(currentTime);
		String path = pathDir + File.separatorChar + dateString + File.separatorChar;

		return path;
	}

}